using System.Workflow.ComponentModel;
using System.Workflow.Activities;
using Microsoft.Crm.Workflow;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using System.Xml;
using System;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using MSA.Integration;
using Microsoft.Crm.Sdk.Query;

namespace MSA.SocialNetworking
{
	[CrmWorkflowActivity("Announce", "MSA Social Networking")]
	public partial class Announce : Activity
	{
		// Override this method with our custom logic
		protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
		{

            string ConsumerKey = string.Empty;
            string ConsumerSecret = string.Empty;

            //Get the Guid from the Workflow
            IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
            IWorkflowContext ctx = contextService.Context;
            ICrmService crmService = ctx.CreateCrmService();
            string recordId = ctx.PrimaryEntityId.ToString();
            string timestamp = DateTime.UtcNow.ToString("yyyyMMddhhmmss");
            string _xslt = string.Empty;


            // Retrieve Global Paramters
           
            // ------------------



            //Get Integration Configuration from CRM i.e. XSLT transform
            ColumnSet cset = new ColumnSet(new String[] { "msa_integrationconfigurationid", "msa_configstring" });
            try
            {
                DynamicEntity dataset = inbound.CrmSearch("msa_integrationconfiguration", "msa_name", "Twitter.Update", cset, crmService);
                _xslt = dataset["msa_configstring"].ToString();


                // Retrieve Global parameters
                DynamicEntity applicationParameters = inbound.CrmSearch("msa_integrationconfiguration", "msa_name", "Twitter.ApplicationParameters", cset, crmService);
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(applicationParameters.Properties["msa_configstring"].ToString());

                ConsumerKey = SettingsConfiguration.GetConfigDataString(doc, "ConsumerKey");
                ConsumerSecret = SettingsConfiguration.GetConfigDataString(doc, "ConsumerSecret");

                //-----------------------------------------------
            }
            catch (Exception e)
            {
                this.ReturnStatus = "Fail";
                return base.Execute(executionContext);
            }
            //end xslt


            _xslt = string.Format(_xslt, recordId);
            Boolean debugflag;
            if (Debug == "true")
            {
                debugflag = true;
            }
            else
            {
                debugflag = false;
            }

            XDocument xDoc = new XDocument();
            msa_twitter twUpdate = new msa_twitter();

            //Update Announcement on Twitter 
           // if(twUpdate.SetCredentials(UserName,Password))
           // {

            oAuthTwitter oAuth = new oAuthTwitter();
            oAuth.ConsumerKey = ConsumerKey;//"GzpBjSoh9dx35PgTP5NztQ";
            oAuth.ConsumerSecret = ConsumerSecret; //"jWTVU2E0irbVmSffJNKeOAvDT6c7DmaGyESVBo9S81w";
            oAuth.Token = Token;
            oAuth.TokenSecret = TokenSecret;
            oAuth.PIN = Pin;
                string returnXml = twUpdate.Update(Announcement);
                xDoc = XDocument.Parse(returnXml);
                inbound.CrmTransaction(crmService, msa_transformation.Transform(returnXml, _xslt, debugflag));
                this.ReturnStatus = "Success";
           // }
           // else
           // {            
           //     this.ReturnStatus = "Fail"; //Need to tie this in with Workflow as to re-trials, notifications etc.
           // }

            //CleanUp
            _xslt = null;
            xDoc = null;
			return base.Execute(executionContext);
		}

		// Allow the user to set the Username that authenticates to Twitter 
		public static DependencyProperty UserNameProperty = DependencyProperty.Register("UserName", typeof(string), typeof(Announce));
		[CrmInput("UserName")]
		public string UserName
		{
			get { return (string)base.GetValue(UserNameProperty); }
			set { base.SetValue(UserNameProperty, value); }
		}

        

		// Allow the user to set the Password 
		public static DependencyProperty PasswordProperty = DependencyProperty.Register("Password", typeof(string), typeof(Announce));
		[CrmInput("Password")]
		public string Password
		{
			get { return (string)base.GetValue(PasswordProperty); }
			set { base.SetValue(PasswordProperty, value); }
		}

        public static DependencyProperty AnnouncementProperty = DependencyProperty.Register("Announcement", typeof(string), typeof(Announce));
        [CrmInput("Announcement")]
        public string Announcement
        {
            get { return (string)base.GetValue(AnnouncementProperty); }
            set { base.SetValue(AnnouncementProperty, value); }
        }

        public static DependencyProperty DebugProperty = DependencyProperty.Register("Debug", typeof(string), typeof(Announce));
        [CrmInput("Debug")]
        public string Debug
        {
            get { return (string)base.GetValue(DebugProperty); }
            set { base.SetValue(DebugProperty, value); }
        }

        public static DependencyProperty TokenProperty = DependencyProperty.Register("Token", typeof(string), typeof(Announce));
        [CrmInput("Token")]
        public string Token
        {
            get { return (string)base.GetValue(TokenProperty); }
            set { base.SetValue(TokenProperty, value); }
        }

        public static DependencyProperty TokenSecretProperty = DependencyProperty.Register("TokenSecret", typeof(string), typeof(Announce));
        [CrmInput("TokenSecret")]
        public string TokenSecret
        {
            get { return (string)base.GetValue(TokenSecretProperty); }
            set { base.SetValue(TokenSecretProperty, value); }
        }

        public static DependencyProperty PinProperty = DependencyProperty.Register("Pin", typeof(string), typeof(Announce));
        [CrmInput("Pin")]
        public string Pin
        {
            get { return (string)base.GetValue(PinProperty); }
            set { base.SetValue(PinProperty, value); }
        }


        //public static DependencyProperty ConsumerKeyProperty = DependencyProperty.Register("ConsumerKey", typeof(string), typeof(Announce));
        //[CrmInput("ConsumerKey")]
        //public string ConsumerKey
        //{
        //    get { return (string)base.GetValue(ConsumerKeyProperty); }
        //    set { base.SetValue(ConsumerKeyProperty, value); }
        //}

        //public static DependencyProperty ConsumerSecretProperty = DependencyProperty.Register("ConsumerSecret", typeof(string), typeof(Announce));
        //[CrmInput("ConsumerSecret")]
        //public string ConsumerSecret
        //{
        //    get { return (string)base.GetValue(ConsumerSecretProperty); }
        //    set { base.SetValue(ConsumerSecretProperty, value); }
        //}


		// Returns the formatted email MailTo Url to the workflow rule for use  
		public static DependencyProperty ReturnStatusProperty = DependencyProperty.Register("ReturnStatus", typeof(string), typeof(Announce));
		[CrmOutput("ReturnStatus")]
		public string ReturnStatus
		{
			get { return (string)base.GetValue(ReturnStatusProperty); }
			set { base.SetValue(ReturnStatusProperty, value); }
		}
	}
}